/**
 * 上传百度 BOS
 */
const QiNiuUrl = 'https://upload.qiniup.com';

import { imService, RongIMLib } from './cloudUtil';

/**
 * 上传七牛云
 * @resolve: 用于下载文件(图片, 音频等)的url
 */
export function uploadQiNiu(fileRes, token, fileType) {
  let filePath = fileRes.tempFilePaths[0];
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: QiNiuUrl,
      filePath: filePath,
      name: 'file',
      formData: {
        token: token,
      },
      success: (res) => {
        // console.log(res)
        //res.data: "{"name": "image_275.png","size": 916,"w": 75,"h": 50,"hash": "Fpa-mZm9FeNj3bWpKAx6h_eHLILN"}"
        let { data } = res;
        const { hash, name } = JSON.parse(data);
        imService.getFileUrl(fileType || RongIMLib.FILE_TYPE.IMAGE, hash, name, res)
          .then(function (data) {
            // console.log('文件 url 为: ', data.downloadUrl);
            resolve(data.downloadUrl);
          })
          .catch(function (error) {
            console.log('获取文件 url 失败', error);
          });
      },
      fail: (res) => {
        console.log('七牛上传失败', res);
      },
    });
  });
}

/*
 压缩图片
 */
export function compressImage(chooseRes) {
  let src = chooseRes.tempFilePaths[0];
  let _this = this;
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: src,
      success(res) {
        console.log('压缩前', res);
        let canvasWidth = res.width; //图片原始长宽
        let canvasHeight = res.height;
        let img = new Image();
        img.src = res.path;
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        canvas.width = canvasWidth / 2;
        canvas.height = canvasHeight / 2;
        console.log(img);
        ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
        canvas.toBlob(function (fileSrc) {
          let imgSrc = window.URL.createObjectURL(fileSrc);
          console.log('压缩后', imgSrc);
          resolve(imgSrc);
          uni.hideLoading();
        });
      },
    });
  });
}

// 调用方法需要用 appImageCompress.call(this, chooseRes , 1)
export function appImageCompress(chooseRes, num = 1) {
  let index = chooseRes.tempFiles[num].path.lastIndexOf('.'); //获取图片地址最后一个点的位置
  let img_type = chooseRes.tempFiles[num].path.substring(
    index + 1,
    chooseRes.tempFiles[num].path.length
  ); //截取图片类型如png jpg
  let img_ori = chooseRes.tempFiles[num].path.substring(0, index); //截取图片原始路径
  let d2 = new Date().getTime(); //时间戳
  //压缩图片
  plus.zip.compressImage(
    {
      src: chooseRes.tempFiles[num].path, //你要压缩的图片地址
      dst: img_ori + d2 + '.' + img_type, //压缩之后的图片地址(注意压缩之后的路径最好和原生路径的位置一样，不然真机上报code-5)
      quality: 10, //[10-100]
    },
    function (e) {
      console.log('Compress success!', e.target);
      //压缩之后路径转base64位的
      //通过URL参数获取目录对象或文件对象
      plus.io.resolveLocalFileSystemURL(e.target, function (entry) {
        // 可通过entry对象操作test.html文件
        entry.file(function (file) {
          //获取文件数据对象
          var fileReader = new plus.io.FileReader(); // 文件系统中的读取文件对象，用于获取文件的内容
          //alert("getFile:" + JSON.stringify(file));
          fileReader.readAsDataURL(file); //以URL编码格式读取文件数据内容
          fileReader.onloadend = function (evt) {
            //读取文件成功完成的回调函数
            console.log(evt.target.result.split(',')[1]); //拿到'data:image/jpeg;base64,'后面的

            chooseRes.tempFiles[num].Base64_Path = evt.target.result.split(
              ','
            )[1];
          };
        });
      });
      that.materialList = that.materialList.concat(chooseRes.tempFiles[num]);
      //利用递归循环来实现多张图片压缩
      if (num == chooseRes.tempFiles.length - 1) {
        return;
      } else {
        that.app_img(num + 1, chooseRes);
      }
      console.log('end', that.materialList);
    },
    function (error) {
      console.log('Compress error!');
      console.log(JSON.stringify(error));
    }
  );
}
